package com.cnn.function.stock.service.impl;

import com.cnn.function.stock.mapper.StockMapper;
import com.cnn.function.stock.pojo.Stock;
import com.cnn.function.stock.pojo.StockExample;
import com.cnn.function.stock.pojo.StockInDetails;
import com.cnn.function.stock.service.StockInDetailsService;
import com.cnn.function.stock.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class StockServiceImpl implements StockService {

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private StockInDetailsService stockInDetailsService;


    @Override
    public void addStock(Stock stock) {
        stockMapper.insert(stock);
    }

    @Override
    public void updateStcok(Stock stock) {

        stockMapper.updateByPrimaryKey(stock);
    }

    @Override
    public Stock getStockById(Long id) {
        return stockMapper.selectByPrimaryKey(id);
    }

    @Override
    public void deleteStock(Long id) {

        stockMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<Stock> getStock() {
        return stockMapper.selectByExample(new StockExample());
    }

    @Override
    public List<Stock> getStockBySku(String sku) {
        StockExample stockExample = new StockExample();
        stockExample.createCriteria().andSkuEqualTo(sku);
        return stockMapper.selectByExample(stockExample);
    }

    @Override
    public void inToStock(StockInDetails stockInDetails) {
        //1.根据sku查询商品
        List<Stock> stockList = this.getStockBySku(stockInDetails.getSku());
        //2.库存表库存数量+入库数量 ，在途数量-入库数量
        Stock stock = stockList.get(0);
        stock.setStockCount(stock.getStockCount() + stockInDetails.getCount());
        //由于缺少前置的订单创建功能，所以这里暂时这么写，正常应该是创建采购订单的时候，就要在这个商品的库存上加需要采购的数量
        stock.setPurchaseCount(stock.getPurchaseCount() < stockInDetails.getCount() ? 0 : stock.getPurchaseCount() - stockInDetails.getCount());
        stockMapper.updateByPrimaryKey(stock);
        //3.入库表中加入入库信息

        //生成入库单号
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
        Date date = new Date();
        String createdate = simpleDateFormat.format(date);
        //从session取操作员信息
//        stockInDetails.setCreatedBy();
        stockInDetails.setEnabled((byte) 1);
        stockInDetails.setCreatedTime(date);
        stockInDetailsService.addStockInDetails(stockInDetails);
        Long id = stockInDetails.getId();
        stockInDetails.setInStockNo(createdate + id);
        stockInDetailsService.updateStockInDetails(stockInDetails);
    }


}
